import React, { useEffect, useRef, useState } from 'react'
import { Button } from 'antd'
import { ProTable } from '@ant-design/pro-components'
import TableComulnUtil from './utils/TableComulnUtil'
import { PlusOutlined } from '@ant-design/icons'

export default React.memo((props) => {
  const [tableColumns, setTableColumns] = useState([])
  const ref = useRef()

  useEffect(()=>{ init() }, [props])

  const init = async() => {
    const tableColumns = TableComulnUtil(props)
    if(props.auths.EDIT || props.auths.DELETE || props.auths.DETAIL){
      tableColumns.push({
        title: '操作',
        valueType: 'option',
        key: 'option',
        render: (text, record, _, action) => {
          const option = []
          if(props.auths.DETAIL){ option.push(<a key="detail" onClick={()=>onDetail(record)}>查看</a>) }
          if(props.auths.EDIT){
            option.push(<a key="editable" onClick={()=>onEdit(record)}>编辑</a>) 
            option.push(<a key="editable" onClick={()=>onReceiving(record)}>接收</a>) 
          }
          if(props.auths.DELETE && record.owner == window.user.id){ option.push(<a key="delete" onClick={()=>onDelete(record)}>删除</a>) }
          return option
        }
      })
    }
    setTableColumns(tableColumns)
  }

  const req = async(req = {}, _sort) => {
    const filter = {
      ...(props.config?.default?.filters || {}),
      ...req
    }
    delete filter.current
    delete filter.pageSize
    const sort = Object.keys(_sort).map(key=>{
      return key.indexOf('.') == -1 ? `${props.table}.${key} ${_sort[key] == 'ascend' ? ' ASC' : ' DESC'}` :`${key} ${_sort[key] == 'ascend' ? ' ASC' : ' DESC'}`
    })
    const data = await request.post(`/api/flow/tasks/${props.menu}`, { page: req.current, pageSize: req.pageSize, filter, sort:[...sort, ...(props.config?.default?.sort || [])] })
    return { data: data.data, success: true, total: data.count }
  }

  const onAdd = () => { }
  const onDetail = (record) => { }
  const onEdit = (record) => { }
  const onDelete = (record) => { }
  const onReceiving = async(record) => {}

  return (
    <ProTable actionRef={ref} toolbar={{title: props.menu}} scroll={{x:true}} cardBordered rowKey={'id'} columns={tableColumns}
      toolBarRender={()=>props.auths.ADD ? [<Button key="button" icon={<PlusOutlined />} onClick={onAdd} type="primary">新建</Button>] : []}
      pagination={{ pageSize: 10 }} request={req}/>
  )
})